package com.yss.reportworld.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.WriteTable;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yss.common.core.constant.RequestDataHelper;
import com.yss.common.core.domain.TreeNode;
import com.yss.common.core.enums.YssStatusEnum;
import com.yss.common.core.exception.BusinessException;
import com.yss.common.core.utils.JdbcUtil;
import com.yss.common.core.utils.StringUtils;
import com.yss.common.core.utils.easyexecl.Custemhandler;
import com.yss.common.core.utils.easyexecl.EasyExeclUtil;
import com.yss.common.core.utils.easyexecl.ExcelListener;
import com.yss.common.core.utils.easyexecl.WaterMarkHandler;
import com.yss.common.core.utils.sql.SqlUtil;
import com.yss.common.core.utils.uuid.IdUtils;
import com.yss.reportworld.domain.rule.*;
import com.yss.reportworld.enums.ReportWorldEnum;
import com.yss.reportworld.mapper.rule.*;
import com.yss.reportworld.service.IDataCustomerService;
import com.yss.reportworld.service.IRCheckTypeService;
import com.yss.reportworld.service.IRuleService;
import com.yss.reportworld.util.TableInfoUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RuleServiceImpl implements IRuleService {
    @Autowired
    private RCheckObjectMapper rCheckObjectMapper;
    @Autowired
    private RConstantMapper rConstantMapper;
    @Autowired
    private RParameterMapper rParameterMapper;
    @Autowired
    private RFunctionMapper rFunctionMapper;
    @Autowired
    private RDatasetParFuncRelationMapper rDatasetParFuncRelationMapper;
    @Autowired
    private RCheckInParameterMapper rCheckInParameterMapper;
    @Autowired
    private RCheckSqlOutParameterMapper rCheckSqlOutParameterMapper;
    @Autowired
    private RCheckRuleMapper rCheckRuleMapper;
    @Autowired
    private RCheckObjectRelMappingMapper rCheckObjectRelMappingMapper;
    @Autowired
    private RCheckObjectRelGroupbyMapper rCheckObjectRelGroupbyMapper;
    @Autowired
    private RObjectSourceSqlRelationMapper rObjectSourceSqlRelationMapper;
    @Autowired
    private RRuleLabelMapper rRuleLabelMapper;
    @Autowired
    private RFunctionTypeMapper rFunctionTypeMapper;
    @Autowired
    private IRCheckTypeService rCheckTypeService;
    @Autowired
    private RFuncInParameterMapper rFuncInParameterMapper;
    @Autowired
    private RFuncReturnParameterMapper rFuncReturnParameterMapper;
    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;
    @Autowired
    private IDataCustomerService dataCustomerService;

    public void downRuleExecl(HttpServletResponse response, RCheckObject rCheckObject) {
        ExcelWriter excelWriter = null;
        try {
            TableInfoUtil.handleTableVersion(rCheckObject.getHisVersion());
            // 数据库来源
            String sourceCode = rCheckObject.getDataBaseType();
            // 校验对象的id
            List<String> ids = null;
            // 规则分类编号
            List<String> ruleTypeIds = new ArrayList<>();
            if (1 == rCheckObject.getExportType()) { //导出方式是规则分类
                ruleTypeIds.add(rCheckObject.getRuleTypeId());
                // 获取所有下级的 规则编码
                ruleTypeIds.addAll(rCheckTypeService.queryRCheckTypeIds(rCheckObject.getRuleTypeId()));
            } else { //检验对象导出
                ids = rCheckObject.getIds();
            }
            List<RCheckObject> checkObjecList = rCheckObjectMapper.selectExport(YssStatusEnum.NORMAL.getCode(), sourceCode, ids, ruleTypeIds);
            checkObjecList = dataCustomerService.handleBusinessPrimaryCustomer(checkObjecList, rCheckObject.getCustomerId(), RCheckObject.class);
            if (StringUtils.isEmpty(checkObjecList)) {
                throw new BusinessException("没有获取到你要导出的校验对象信息，请检查！");
            }
            // 获取所有规则类型的名称集合
            Map<String, String> map = rCheckTypeService.getRuleTypeName();
            if (StringUtils.isEmpty(map)) {
                throw new BusinessException("没有获取到你要导出的规则分类信息，请检查！");
            }
            for (RCheckObject objectTemplate : checkObjecList) {
                objectTemplate.setRuleTypeId(map.get(objectTemplate.getRuleTypeId()));
            }
            List<String> checkObjecIds = checkObjecList.stream().map(RCheckObject::getId).collect(Collectors.toList());
            if (StringUtils.isEmpty(checkObjecIds)) {
                throw new BusinessException("没有获取到你要导出的校验对象信息，请检查！");
            }
            Map<Integer, List<RCheckObject>> collect = checkObjecList.stream()
                    .collect(Collectors.groupingBy(RCheckObject::getSubType));
            // 获取关联校验对象id
            List<String> complexIds = Optional.ofNullable(collect.get(1)).orElse(new ArrayList<RCheckObject>())
                    .stream().map(RCheckObject::getId).collect(Collectors.toList());
            // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(EasyExeclUtil.headWriteCellStyle(), EasyExeclUtil.contentWriteCellStyle());
            excelWriter = EasyExcel.write(response.getOutputStream())
                    .inMemory(true)
                    .registerWriteHandler(new WaterMarkHandler())
                    .excelType(ExcelTypeEnum.XLSX)
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(new Custemhandler())
                    .password(ReportWorldEnum.RULE_PASSWORD.getCode())
                    .build();
            WriteSheet sheetConstant = EasyExcel.writerSheet(0, RConstant.SHEET_NAME).build();
            WriteSheet sheetParameter = EasyExcel.writerSheet(1, RParameter.SHEET_NAME).build();
            WriteSheet sheetFunction = EasyExcel.writerSheet(2, RFunction.SHEET_NAME).build();
            WriteSheet sheetCheckObject = EasyExcel.writerSheet(3, RCheckObject.SHEET_NAME).build();
            WriteSheet sheetRelation = EasyExcel.writerSheet(4, RDatasetParFuncRelation.SHEET_NAME).build();
            WriteSheet sheetInParameter = EasyExcel.writerSheet(5, RCheckInParameter.SHEET_NAME).build();
            WriteSheet sheetOutParameter = EasyExcel.writerSheet(6, RCheckSqlOutParameter.SHEET_NAME).build();
            WriteSheet sheetRule = EasyExcel.writerSheet(7, RCheckRule.SHEET_NAME).build();

            WriteSheet sheetRelMapping = EasyExcel.writerSheet(8, RCheckObjectRelMapping.SHEET_NAME).build();
            WriteSheet sheetGroupBy = EasyExcel.writerSheet(9, RCheckObjectRelGroupby.SHEET_NAME).build();
            WriteSheet sheetRelBind = EasyExcel.writerSheet(10, RObjectSourceSqlRelation.SHEET_NAME).build();

            WriteTable tableConstant = EasyExcel.writerTable().head(RConstant.class).needHead(true).build();
            WriteTable tableParameter = EasyExcel.writerTable().head(RParameter.class).needHead(true).build();
            WriteTable tableFunction = EasyExcel.writerTable().head(RFunction.class).needHead(true).build();
            WriteTable tableCheckObject = EasyExcel.writerTable().head(RCheckObject.class).needHead(true).build();
            WriteTable tableRelation = EasyExcel.writerTable().head(RDatasetParFuncRelation.class).needHead(true).build();
            WriteTable tableInParameter = EasyExcel.writerTable().head(RCheckInParameter.class).needHead(true).build();
            WriteTable tableOutParameter = EasyExcel.writerTable().head(RCheckSqlOutParameter.class).needHead(true).build();
            WriteTable tableRule = EasyExcel.writerTable().head(RCheckRule.class).needHead(true).build();

            WriteTable tableRelMapping = EasyExcel.writerTable().head(RCheckObjectRelMapping.class).needHead(true).build();
            WriteTable tableGroupBy = EasyExcel.writerTable().head(RCheckObjectRelGroupby.class).needHead(true).build();
            WriteTable tableRelBind = EasyExcel.writerTable().head(RObjectSourceSqlRelation.class).needHead(true).build();

            List<RConstant> rConstantList = rConstantMapper.selectExport(YssStatusEnum.NORMAL.getCode(), sourceCode, ObjectUtils.defaultIfNull(checkObjecIds, new ArrayList<>()), ObjectUtils.defaultIfNull(ruleTypeIds, new ArrayList<>()));
            rConstantList = dataCustomerService.handleBusinessPrimaryCustomer(rConstantList, rCheckObject.getCustomerId(), RConstant.class);
            EasyExeclUtil.write(rConstantList, excelWriter, sheetConstant, tableConstant);
            List<RParameter> rParameterList = rParameterMapper.selectExport(YssStatusEnum.NORMAL.getCode(), sourceCode, checkObjecIds, ruleTypeIds);
            rParameterList = dataCustomerService.handleBusinessPrimaryCustomer(rParameterList, rCheckObject.getCustomerId(), RParameter.class);
            EasyExeclUtil.write(rParameterList, excelWriter, sheetParameter, tableParameter);
            List<RFunction> rFunctionList = rFunctionMapper.selectExport(YssStatusEnum.NORMAL.getCode(), sourceCode, checkObjecIds, ruleTypeIds);
            rFunctionList = dataCustomerService.handleBusinessPrimaryCustomer(rFunctionList, rCheckObject.getCustomerId(), RFunction.class);
            rFunctionList = this.hanldFunction(rFunctionList);
            EasyExeclUtil.write(rFunctionList, excelWriter, sheetFunction, tableFunction);
            EasyExeclUtil.write(checkObjecList, excelWriter, sheetCheckObject, tableCheckObject);
            List<RDatasetParFuncRelation> rDatasetParFuncRelationList = rDatasetParFuncRelationMapper.selectExport(YssStatusEnum.NORMAL.getCode(), sourceCode, checkObjecIds, ruleTypeIds);
            rDatasetParFuncRelationList = dataCustomerService.handleBusinessPrimaryCustomer(rDatasetParFuncRelationList, rCheckObject.getCustomerId(), RDatasetParFuncRelation.class);
            EasyExeclUtil.write(rDatasetParFuncRelationList, excelWriter, sheetRelation, tableRelation);
            List<RCheckInParameter> rCheckInParameterList = rCheckInParameterMapper.selectExport(YssStatusEnum.NORMAL.getCode(), sourceCode, checkObjecIds, ruleTypeIds);
            rCheckInParameterList = dataCustomerService.handleBusinessPrimaryCustomer(rCheckInParameterList, rCheckObject.getCustomerId(), RCheckInParameter.class);
            EasyExeclUtil.write(rCheckInParameterList, excelWriter, sheetInParameter, tableInParameter);
            List<RCheckSqlOutParameter> rCheckSqlOutParameterList = rCheckSqlOutParameterMapper.selectExport(YssStatusEnum.NORMAL.getCode(), sourceCode, checkObjecIds, ruleTypeIds);
            rCheckSqlOutParameterList = dataCustomerService.handleBusinessPrimaryCustomer(rCheckSqlOutParameterList, rCheckObject.getCustomerId(), RCheckSqlOutParameter.class);
            EasyExeclUtil.write(rCheckSqlOutParameterList, excelWriter, sheetOutParameter, tableOutParameter);
            // 规则列表
            List<RCheckRule> rCheckRuleList = rCheckRuleMapper.selectExport(YssStatusEnum.NORMAL.getCode(), sourceCode, checkObjecIds, ruleTypeIds);
            rCheckRuleList = dataCustomerService.handleBusinessPrimaryCustomer(rCheckRuleList, rCheckObject.getCustomerId(), RCheckRule.class);
            rCheckRuleList = this.addLabel(rCheckRuleList);
            EasyExeclUtil.write(rCheckRuleList, excelWriter, sheetRule, tableRule);
            if (!CollectionUtils.isEmpty(complexIds)) {
                List<RCheckObjectRelMapping> rCheckObjectRelMappingList = rCheckObjectRelMappingMapper.selectExport(YssStatusEnum.NORMAL.getCode(), sourceCode, complexIds, ruleTypeIds);
                rCheckObjectRelMappingList = dataCustomerService.handleBusinessPrimaryCustomer(rCheckObjectRelMappingList, rCheckObject.getCustomerId(), RCheckObjectRelMapping.class);
                EasyExeclUtil.write(rCheckObjectRelMappingList, excelWriter, sheetRelMapping, tableRelMapping);
                List<RCheckObjectRelGroupby> rCheckObjectRelGroupbyList = rCheckObjectRelGroupbyMapper.selectExport(YssStatusEnum.NORMAL.getCode(), sourceCode, complexIds, ruleTypeIds);
                rCheckObjectRelGroupbyList = dataCustomerService.handleBusinessPrimaryCustomer(rCheckObjectRelGroupbyList, rCheckObject.getCustomerId(), RCheckObjectRelGroupby.class);
                EasyExeclUtil.write(rCheckObjectRelGroupbyList, excelWriter, sheetGroupBy, tableGroupBy);
                List<RObjectSourceSqlRelation> rObjectSourceSqlRelationList = rObjectSourceSqlRelationMapper.selectExport(YssStatusEnum.NORMAL.getCode(), sourceCode, complexIds, ruleTypeIds);
                rObjectSourceSqlRelationList = dataCustomerService.handleBusinessPrimaryCustomer(rObjectSourceSqlRelationList, rCheckObject.getCustomerId(), RObjectSourceSqlRelation.class);
                EasyExeclUtil.write(rObjectSourceSqlRelationList, excelWriter, sheetRelBind, tableRelBind);
            }
        } catch (Exception ex) {
            log.error("报表世界规则文件导出失败" + ex.getMessage());
            throw new BusinessException("报表世界规则文件导出失败！" + ex.getMessage());
        } finally {
            if (null != excelWriter) {
                excelWriter.finish();
            }
            RequestDataHelper.removeThreadLocal();
        }
    }

    // 规则列表 的标签处理 追加标签
    public List<RCheckRule> addLabel(List<RCheckRule> rCheckRuleList) {
        if (StringUtils.isEmpty(rCheckRuleList)) {
            return rCheckRuleList;
        }
        // 规则列表里的标签出来
        QueryWrapper<RRuleLabel> rRuleLabelQueryWrapper = new QueryWrapper<>();
        //rRuleLabelQueryWrapper.in("ID", listRuleLabelId);
        rRuleLabelQueryWrapper.eq("RW_DB_STATUS", YssStatusEnum.NORMAL.getCode());
        // 获取所有标签的map集合
        Map<String, String> labelMap = rRuleLabelMapper.selectList(rRuleLabelQueryWrapper).
                stream().collect(Collectors.toMap(e -> e.getId(), e -> e.getName()));
        if (StringUtils.isEmpty(labelMap)) {
            return rCheckRuleList;
        }
        List<RCheckRule> list = new ArrayList<>();
        RCheckRule last = null;
        for (RCheckRule item : rCheckRuleList) {
            if (null == last || !last.getId().equals(item.getId())) {
                list.add(last = item);
            }
            last.addLabel(labelMap.get(item.getRuleLabelId()));
        }
        return list;

    }

    // 函数列表 函数分类处理
    public List<RFunction> hanldFunction(List<RFunction> rFunctionList) {
        if (StringUtils.isEmpty(rFunctionList)) {
            return rFunctionList;
        }
        List<RFunction> list = new ArrayList<>();
        Map<String, String> map = this.getFunctionTypeName();
        RFunction last = null;
        for (RFunction item : rFunctionList) {
            if (null == last || !last.getId().equals(item.getId())) {
                list.add(last = item);
            }
            if (StringUtils.isNotEmpty(map) && map.containsKey(item.getFuncTypeId())) {
                item.setFuncTypeId(map.get(item.getFuncTypeId()));
            }
            QueryWrapper<RFuncInParameter> inParameterQueryWrapper = new QueryWrapper<>();
            inParameterQueryWrapper.eq("FUNC_ID", item.getId());
            inParameterQueryWrapper.orderByAsc("SORTS");
            List<RFuncInParameter> rFuncInParameters = rFuncInParameterMapper.selectList(inParameterQueryWrapper);
            if (StringUtils.isNotEmpty(rFuncInParameters)) {
                StringBuffer buffer = new StringBuffer();
                for (RFuncInParameter inParameter : rFuncInParameters) {
                    buffer.append(FuncParamEnum.getEnumDesc(inParameter.getTypes())).append(" ").append(inParameter.getCode()).append(" ").append(inParameter.getName()).append("\r\n");
                }
                item.setInParams(buffer.toString());
            }
            QueryWrapper<RFuncReturnParameter> rFuncReturnParameterQueryWrapper = new QueryWrapper<>();
            rFuncReturnParameterQueryWrapper.eq("FUNC_ID", item.getId());
            rFuncReturnParameterQueryWrapper.orderByAsc("SORTS");
            List<RFuncReturnParameter> rFuncReturnParameters = rFuncReturnParameterMapper.selectList(rFuncReturnParameterQueryWrapper);
            if (StringUtils.isNotEmpty(rFuncReturnParameters)) {
                StringBuffer buffer = new StringBuffer();
                for (RFuncReturnParameter returnParameter : rFuncReturnParameters) {
                    buffer.append(FuncParamEnum.getEnumDesc(returnParameter.getTypes())).append(" ").append(returnParameter.getCode()).append(" ").append(returnParameter.getName()).append("\r\n");
                }
                item.setReturnParams(buffer.toString());
            }
        }
        return list;
    }

    public static final String TREE_SEPARATOR = "/";

    public Map<String, String> getFunctionTypeName() {
        Map<String, String> tileMap = new HashMap<>();
        List<TreeNode> list = this.selectRFunctionTypeTreeList();
        if (StringUtils.isEmpty(list)) {
            return tileMap;
        }
        list.forEach(e -> buildPathValue(tileMap, null, e, TREE_SEPARATOR));
        return tileMap;
    }

    private static <T extends TreeNode> void buildPathValue(Map<String, String> tileMap, String parentPath, T treeNode, String separator) {
        String path = null == parentPath ? treeNode.getLabel() : (parentPath + separator + treeNode.getLabel());
        tileMap.put(treeNode.getId(), path);

        List<TreeNode> children = treeNode.getChildren();
        if (StringUtils.isNotEmpty(children)) {
            children.forEach(e -> buildPathValue(tileMap, path, e, separator));
        }
    }

    /**
     * 检验规则的树结构信息
     *
     * @return 检验规则树信息集合
     */
    public List<TreeNode> selectRFunctionTypeTreeList() {
        List<TreeNode> list = new ArrayList<>();
        QueryWrapper<RFunctionType> wrapper = new QueryWrapper<>();
        wrapper.eq("RW_DB_STATUS", YssStatusEnum.NORMAL.getCode());
        List<RFunctionType> rFunctionTypeList = rFunctionTypeMapper.selectList(wrapper);
        if (StringUtils.isEmpty(rFunctionTypeList)) {
            return list;
        }
        for (RFunctionType rFunctionType : rFunctionTypeList) {
            if (StringUtils.isNull(rFunctionType)) {
                continue;
            }
            if (StringUtils.isEmpty(rFunctionType.getParentId())) {
                rFunctionType.setParentId("0");
            }
        }
        List<String> tempList = rFunctionTypeList.stream().map(RFunctionType::getId).collect(Collectors.toList());
        Set<String> set = new HashSet<>();
        for (RFunctionType rFunctionType : rFunctionTypeList) {
            if (StringUtils.isNull(rFunctionType)) {
                continue;
            }
            if (set.contains(rFunctionType.getParentId()) || tempList.contains(rFunctionType.getParentId())) {
                continue;
            }
            list.addAll(this.recursionTree(rFunctionType.getParentId(), rFunctionTypeList));
            set.add(rFunctionType.getParentId());
        }
        return list;
    }

    private List<TreeNode> recursionTree(String id, List<RFunctionType> listRFunctionType) {
        List<TreeNode> list = new ArrayList<>();
        for (RFunctionType rCheckType : listRFunctionType) {
            if (!id.equals(rCheckType.getParentId())) {
                continue;
            }
            TreeNode treeNode = this.handRFunctionTypeToNode(rCheckType);
            List<TreeNode> children = recursionTree(rCheckType.getId(), listRFunctionType);
            treeNode.setChildren(children);
            list.add(treeNode);
        }
        return list;
    }

    /**
     * 将业务功能转化成TreeNode
     */
    private TreeNode handRFunctionTypeToNode(RFunctionType rFunctionType) {
        TreeNode node = new TreeNode();
        node.setId(rFunctionType.getId());
        node.setParentId(rFunctionType.getParentId());
        node.setLabel(rFunctionType.getName());
        return node;
    }

    // 函数的 map key是函数名称，value是id
    private Map<String, String> rFunctionMap = new HashMap<>();
    // 检验对象的 map key是检验对象，value是id
    private Map<String, String> rCheckObjectMap = new HashMap<>();
    // 常量分类
    private Map<String, String> rConstantType = new HashMap<>();
    // 参数分类
    private Map<String, String> rParameterType = new HashMap<>();

    /**
     * 生成脚本
     *
     * @param multipartFile
     * @return
     */
    public String getRuleSql(MultipartFile multipartFile, String hisVersion) {
        StringBuffer sqlBuffer = new StringBuffer();
        ExcelReader excelReader = null;
        try {
            String multipartFileName = multipartFile.getOriginalFilename();
            // 获取文件后缀
            String prefix = multipartFileName.substring(multipartFileName.lastIndexOf("."));
            if (!StringUtils.oneCase(prefix.toUpperCase(), ".XLSX")) {
                throw new BusinessException("请导入xlsx格式文件");
            }
            excelReader = EasyExcel.read(multipartFile.getInputStream()).password(ReportWorldEnum.RULE_PASSWORD.getCode()).build();
            EasyExeclUtil.setReadOrder(excelReader, RConstant.SHEET_NAME, RParameter.SHEET_NAME, RFunction.SHEET_NAME, RCheckObject.SHEET_NAME,
                    RDatasetParFuncRelation.SHEET_NAME, RCheckInParameter.SHEET_NAME, RCheckSqlOutParameter.SHEET_NAME, RCheckRule.SHEET_NAME,
                    RCheckObjectRelMapping.SHEET_NAME, RCheckObjectRelGroupby.SHEET_NAME, RObjectSourceSqlRelation.SHEET_NAME);
            ExcelListener<RConstant> rConstantExcelListener = new ExcelListener<>();
            ExcelListener<RParameter> rParameterExcelListener = new ExcelListener<>();
            ExcelListener<RFunction> rFunctionExcelListener = new ExcelListener<>();
            ExcelListener<RCheckObject> rCheckObjectExcelListener = new ExcelListener<>();
            ExcelListener<RDatasetParFuncRelation> rDatasetParFuncRelationExcelListener = new ExcelListener<>();
            ExcelListener<RCheckInParameter> rCheckInParameterExcelListener = new ExcelListener<>();
            ExcelListener<RCheckSqlOutParameter> rCheckSqlOutParameterExcelListener = new ExcelListener<>();
            ExcelListener<RCheckRule> rCheckRuleExcelListener = new ExcelListener<>();

            ExcelListener<RCheckObjectRelMapping> rCheckObjectRelMappingExcelListener = new ExcelListener<>();
            ExcelListener<RCheckObjectRelGroupby> rCheckObjectRelGroupbyExcelListener = new ExcelListener<>();
            ExcelListener<RObjectSourceSqlRelation> rObjectSourceSqlRelationExcelListener = new ExcelListener<>();
            // 从文件中读取到数据
            ReadSheet rConstantExcelSheet = EasyExcel.readSheet(RConstant.SHEET_NAME).head(RConstant.class).headRowNumber(2).registerReadListener(rConstantExcelListener).build();
            ReadSheet rParameterExcelSheet = EasyExcel.readSheet(RParameter.SHEET_NAME).head(RParameter.class).headRowNumber(2).registerReadListener(rParameterExcelListener).build();
            ReadSheet rFunctionExcelSheet = EasyExcel.readSheet(RFunction.SHEET_NAME).head(RFunction.class).headRowNumber(2).registerReadListener(rFunctionExcelListener).build();
            ReadSheet rCheckObjectExcelSheet = EasyExcel.readSheet(RCheckObject.SHEET_NAME).head(RCheckObject.class).headRowNumber(2).registerReadListener(rCheckObjectExcelListener).build();
            ReadSheet rDatasetParFuncRelationExcelSheet = EasyExcel.readSheet(RDatasetParFuncRelation.SHEET_NAME).head(RDatasetParFuncRelation.class).headRowNumber(2).registerReadListener(rDatasetParFuncRelationExcelListener).build();
            ReadSheet rCheckInParameterExcelSheet = EasyExcel.readSheet(RCheckInParameter.SHEET_NAME).head(RCheckInParameter.class).headRowNumber(2).registerReadListener(rCheckInParameterExcelListener).build();
            ReadSheet rCheckSqlOutParameterExcelSheet = EasyExcel.readSheet(RCheckSqlOutParameter.SHEET_NAME).head(RCheckSqlOutParameter.class).headRowNumber(2).registerReadListener(rCheckSqlOutParameterExcelListener).build();
            ReadSheet rCheckRuleExcelSheet = EasyExcel.readSheet(RCheckRule.SHEET_NAME).head(RCheckRule.class).headRowNumber(2).registerReadListener(rCheckRuleExcelListener).build();

            ReadSheet rCheckObjectRelMappingExcelSheet = EasyExcel.readSheet(RCheckObjectRelMapping.SHEET_NAME).head(RCheckObjectRelMapping.class).headRowNumber(2).registerReadListener(rCheckObjectRelMappingExcelListener).build();
            ReadSheet rCheckObjectRelGroupbyExcelSheet = EasyExcel.readSheet(RCheckObjectRelGroupby.SHEET_NAME).head(RCheckObjectRelGroupby.class).headRowNumber(2).registerReadListener(rCheckObjectRelGroupbyExcelListener).build();
            ReadSheet rObjectSourceSqlRelationExcelSheet = EasyExcel.readSheet(RObjectSourceSqlRelation.SHEET_NAME).head(RObjectSourceSqlRelation.class).headRowNumber(2).registerReadListener(rObjectSourceSqlRelationExcelListener).build();
            excelReader.read(rConstantExcelSheet, rParameterExcelSheet, rFunctionExcelSheet, rCheckObjectExcelSheet, rDatasetParFuncRelationExcelSheet, rCheckInParameterExcelSheet,
                    rCheckSqlOutParameterExcelSheet, rCheckRuleExcelSheet, rCheckObjectRelMappingExcelSheet, rCheckObjectRelGroupbyExcelSheet, rObjectSourceSqlRelationExcelSheet);
            TableInfoUtil.handleTableVersion(hisVersion); // 替换表名
            this.initRuleSql(hisVersion);
            List<RConstant> rConstantList = rConstantExcelListener.getDatas();
            sqlBuffer.append(this.getRConstantSql(rConstantList));
            List<RParameter> rParameterList = rParameterExcelListener.getDatas();
            sqlBuffer.append(this.getRParameterSql(rParameterList));
            List<RFunction> rFunctionList = rFunctionExcelListener.getDatas();
            sqlBuffer.append(this.getRFunctionSql(rFunctionList));
            List<RCheckObject> rCheckObjectList = rCheckObjectExcelListener.getDatas();
            sqlBuffer.append(this.getRCheckObjectSql(rCheckObjectList));
            List<RDatasetParFuncRelation> rDatasetParFuncRelationList = rDatasetParFuncRelationExcelListener.getDatas();
            sqlBuffer.append(this.getRDatasetParFuncRelationSql(rDatasetParFuncRelationList));
            List<RCheckInParameter> rCheckInParameterList = rCheckInParameterExcelListener.getDatas();
            sqlBuffer.append(this.getRCheckInParameterSql(rCheckInParameterList));
            List<RCheckSqlOutParameter> rCheckSqlOutParameterList = rCheckSqlOutParameterExcelListener.getDatas();
            sqlBuffer.append(this.getRCheckSqlOutParameterSql(rCheckSqlOutParameterList));
            List<RCheckRule> rCheckRuleList = rCheckRuleExcelListener.getDatas();
            sqlBuffer.append(this.getRCheckRuleSql(rCheckRuleList));
            List<RCheckObjectRelMapping> rCheckObjectRelMappingList = rCheckObjectRelMappingExcelListener.getDatas();
            sqlBuffer.append(this.getRCheckObjectRelMapping(rCheckObjectRelMappingList));
            List<RCheckObjectRelGroupby> rCheckObjectRelGroupbyList = rCheckObjectRelGroupbyExcelListener.getDatas();
            sqlBuffer.append(this.geRCheckObjectRelGroupby(rCheckObjectRelGroupbyList));
            List<RObjectSourceSqlRelation> rObjectSourceSqlRelationList = rObjectSourceSqlRelationExcelListener.getDatas();
            sqlBuffer.append(this.getRObjectSourceSqlRelation(rObjectSourceSqlRelationList));
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException("生成校验规则的SQL语句失败：" + ex.getMessage());
        } finally {
            RequestDataHelper.removeThreadLocal();
        }
        return sqlBuffer.toString();
    }

    // 初始化获取常量，参数和函数
    private void initRuleSql(String version) {
        ResultSet rs = null;
        PreparedStatement pStemtSelect = null;
        Connection connection = null;
        try {
            // 初始化
            rFunctionMap = new HashMap<>();
            rCheckObjectMap = new HashMap<>();
            rConstantType = new HashMap<>();
            rParameterType = new HashMap<>();
            connection = dataSource.getConnection();
            if (null == connection) {
                throw new BusinessException("获取数据库连接出错，请稍后重试！");
            }
            String versionSuffix = TableInfoUtil.getVersionSuffix(version);
            String sql = "SELECT ID,CONSTANT_ID,TRUE_VAL FROM RW_DB_R_CONSTANT" + versionSuffix;
            pStemtSelect = connection.prepareStatement(sql);
            rs = pStemtSelect.executeQuery();
            while (rs.next()) {
                rConstantType.put(rs.getString("TRUE_VAL"), rs.getString("ID"));
            }
            rs.close();
            sql = "SELECT ID,NAME from RW_DB_R_PARAMETER" + versionSuffix;
            pStemtSelect = connection.prepareStatement(sql);
            rs = pStemtSelect.executeQuery();
            while (rs.next()) {
                rParameterType.put(rs.getString("NAME"), rs.getString("ID"));
            }
            rs.close();
        } catch (Exception ex) {
            throw new BusinessException("获取校验规则的分组，模板和层级信息出错！" + ex.getMessage());
        } finally {
            try {
                JdbcUtil.close(rs, pStemtSelect, connection);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }

    /**
     * 常量列表 的SQl生成
     *
     * @param rConstantList
     * @return
     */
    private String getRConstantSql(List<RConstant> rConstantList) {
        if (StringUtils.isEmpty(rConstantList)) {
            return "";
        }
        for (RConstant rConstant : rConstantList) {
            rConstant.setId(IdUtils.fastSimpleUUID());
            rConstant.setStatus(YssStatusEnum.NORMAL.getCode());
        }
        return SqlUtil.getSqlByList("R_CONSTANT", rConstantList, RConstant.class);
    }

    /**
     * 参数列表 的SQl生成
     *
     * @param rParameterList
     * @return
     */
    private String getRParameterSql(List<RParameter> rParameterList) {
        if (StringUtils.isEmpty(rParameterList)) {
            return "";
        }
        for (RParameter rParameter : rParameterList) {
            rParameter.setId(IdUtils.fastSimpleUUID());
            rParameter.setStatus(YssStatusEnum.NORMAL.getCode());
        }
        return SqlUtil.getSqlByList("R_PARAMETER", rParameterList, RParameter.class);
    }

    /**
     * 函数列表和函数类型 的SQl生成
     *
     * @param rFunctionList
     * @return
     */
    private String getRFunctionSql(List<RFunction> rFunctionList) {
        if (StringUtils.isEmpty(rFunctionList)) {
            return "";
        }
        // 文件里读取的，id先设置为空
        for (RFunction rFunction : rFunctionList) {
            rFunctionMap.put(rFunction.getFunName(), null);
        }
        StringBuffer sqlBuffer = new StringBuffer();
        // 查询标准库是否存在
        Map<String, String> rFunctionMapStaMap = new HashMap<>();
        List<RFunction> functionList = rFunctionMapper.selectList(new QueryWrapper<>());
        if (StringUtils.isNotEmpty(functionList)) {
            for (RFunction function : functionList) {
                rFunctionMapStaMap.put(function.getFunName(), function.getId());
            }
        }
        rFunctionMap.putAll(rFunctionMapStaMap);
        for (Map.Entry<String, String> entry : rFunctionMap.entrySet()) {
            if (StringUtils.isNotEmpty(entry.getValue())) {
                continue;
            }
            entry.setValue(IdUtils.fastSimpleUUID());
        }
        // 标准库你的函数类型
        Map<String, String> map = this.getFunctionTypeName();
        List<RFunctionType> rFunctionTypeList = new ArrayList<>();
        Map<String, String> rFunctionTypeMap = new HashMap<>();
        for (RFunction rFunction : rFunctionList) {
            // 用“/”拼接的,通过value获取可以，如果没有就要新增一个
            String functTypeId = rFunction.getFuncTypeId();
            if (!map.containsValue(functTypeId)) {  // 不存在就要新建函数类
                String[] functTypeIdArr = rFunction.getFuncTypeId().split(TREE_SEPARATOR);
                String parentId = "", idLast = "";
                StringJoiner typeName = new StringJoiner(TREE_SEPARATOR);
                for (int i = 0; i < functTypeIdArr.length; i++) {
                    RFunctionType rFunctionType = new RFunctionType();
                    String id = IdUtils.fastSimpleUUID();
                    if (i == functTypeIdArr.length - 1) {
                        idLast = id;
                    }
                    rFunctionType.setId(id);
                    rFunctionType.setName(functTypeIdArr[i]);
                    rFunctionType.setParentId(parentId);
                    rFunctionType.setStatus(YssStatusEnum.NORMAL.getCode());
                    typeName.add(functTypeIdArr[i]);
                    // 已经存在的上级id和名称
                    if (rFunctionTypeMap.containsKey(rFunctionType.getParentId() + rFunctionType.getName())) {
                        parentId = rFunctionTypeMap.get(rFunctionType.getParentId() + rFunctionType.getName());
                    } else {
                        parentId = id;
                        rFunctionTypeList.add(rFunctionType);
                    }
                    rFunctionTypeMap.put(rFunctionType.getParentId() + rFunctionType.getName(), id);
                }
                map.put(idLast, typeName.toString());
            }
            boolean falg = false;
            for (Map.Entry<String, String> m : map.entrySet()) {
                if (functTypeId.equals(m.getValue())) {
                    functTypeId = m.getKey();
                    falg = true;
                    break;
                }
            }
            if (!falg) {
                throw new BusinessException("函数信息表中的函数类型没有找到对应的，请检查" + functTypeId);
            }
            rFunction.setId(rFunctionMap.get(rFunction.getFunName()));
            rFunction.setFuncTypeId(functTypeId);
            rFunction.setStatus(YssStatusEnum.NORMAL.getCode());
            String[] arrReturnParams = rFunction.getReturnParams().split("\n");
            for (String returnParams : arrReturnParams) {
                String[] arr = returnParams.split(" ");
                sqlBuffer.append("INSERT INTO R_FUNC_RETURN_PARAMETER (ID, FUNC_ID, CODE, NAME, TYPES, SORTS, CREATE_USER, CREATE_TIME, UPDATE_USER, UPDATE_TIME, STATUS) " +
                        "VALUES('" + IdUtils.fastSimpleUUID() + "', '" + rFunction.getId() + "', '" + arr[1] + "', '" + arr[2] + "', " + FuncParamEnum.getEnumCode(arr[0]) +
                        ", NULL, NULL, SYSDATE, NULL, SYSDATE, " + YssStatusEnum.NORMAL.getCode() + ");").append("\r\n");
            }
            String[] arrInParams = rFunction.getInParams().split("\n");
            for (String inParams : arrInParams) {
                String[] arr = inParams.split(" ");
                sqlBuffer.append("INSERT INTO R_FUNC_IN_PARAMETER (ID, FUNC_ID, CODE, NAME, TYPES, DEFAULT_VAL, SORTS, CREATE_USER, CREATE_TIME, UPDATE_USER, UPDATE_TIME, STATUS) " +
                        "VALUES('" + IdUtils.fastSimpleUUID() + "', '" + rFunction.getId() + "', '" + arr[1] + "', '" + arr[2] + "', " + FuncParamEnum.getEnumCode(arr[0]) +
                        ", NULL, 1, NULL, SYSDATE, NULL, SYSDATE, " + YssStatusEnum.NORMAL.getCode() + ");").append("\r\n");
            }

        }
        sqlBuffer.append(SqlUtil.getSqlByList("R_FUNCTION_TYPE", rFunctionTypeList, RFunctionType.class));
        sqlBuffer.append(SqlUtil.getSqlByList("R_FUNCTION", rFunctionList, RFunction.class));
        return sqlBuffer.toString();
    }

    /**
     * 注册校验对象和校验类型 生成SQl
     *
     * @param rCheckObjectList
     * @return
     */
    private String getRCheckObjectSql(List<RCheckObject> rCheckObjectList) {
        if (StringUtils.isEmpty(rCheckObjectList)) {
            return "";
        }
        // 文件里读取的，id先设置为空
        for (RCheckObject rCheckObject : rCheckObjectList) {
            rCheckObjectMap.put(rCheckObject.getCheckCode(), null);
        }
        StringBuffer sqlBuffer = new StringBuffer();
        Map<String, String> rCheckObjectMapStaMap = rCheckObjectMapper.selectList(new QueryWrapper<>()).
                stream().collect(Collectors.toMap(e -> e.getCheckCode(), e -> e.getId()));
        rCheckObjectMap.putAll(rCheckObjectMapStaMap);
        for (Map.Entry<String, String> entry : rCheckObjectMap.entrySet()) {
            if (StringUtils.isNotEmpty(entry.getValue())) {
                continue;
            }
            entry.setValue(IdUtils.fastSimpleUUID());
        }
        // 获取所有规则类型的名称集合
        Map<String, String> map = rCheckTypeService.getRuleTypeName();
        List<RCheckType> rCheckTypeList = new ArrayList<>();
        Map<String, String> rCheckTypMap = new HashMap<>();
        for (RCheckObject rCheckObject : rCheckObjectList) {
            String ruleTypeId = rCheckObject.getRuleTypeId();
            if (!map.containsValue(ruleTypeId)) {  // 不存在就要新建函数类
                String[] ruleTypeIdArr = rCheckObject.getRuleTypeId().split(TREE_SEPARATOR);
                String parentId = "", idLast = "";
                StringJoiner typeName = new StringJoiner(TREE_SEPARATOR);
                for (int i = 0; i < ruleTypeIdArr.length; i++) {
                    RCheckType rCheckType = new RCheckType();
                    String id = IdUtils.fastSimpleUUID();
                    if (i == ruleTypeIdArr.length - 1) {
                        idLast = id;
                    }
                    rCheckType.setId(id);
                    rCheckType.setName(ruleTypeIdArr[i]);
                    rCheckType.setParentId(parentId);
                    rCheckType.setStatus(YssStatusEnum.NORMAL.getCode());
                    // 已经存在的上级id和名称
                    if (rCheckTypMap.containsKey(rCheckType.getParentId() + rCheckType.getName())) {
                        parentId = rCheckTypMap.get(rCheckType.getParentId() + rCheckType.getName());
                    } else {
                        parentId = id;
                        rCheckTypeList.add(rCheckType);
                    }
                    rCheckTypMap.put(rCheckType.getParentId() + rCheckType.getName(), id);
                    typeName.add(ruleTypeIdArr[i]);
                }
                map.put(idLast, typeName.toString());
            }
            boolean falg = false;
            for (Map.Entry<String, String> m : map.entrySet()) {
                if (ruleTypeId.equals(m.getValue())) {
                    ruleTypeId = m.getKey();
                    falg = true;
                    break;
                }
            }
            if (!falg) {
                throw new BusinessException("注册校验对象中的分类没有找到，请检查" + ruleTypeId);
            }
            rCheckObject.setId(rCheckObjectMap.get(rCheckObject.getCheckCode()));
            rCheckObject.setRuleTypeId(ruleTypeId);
            rCheckObject.setStatus(YssStatusEnum.NORMAL.getCode());
            rCheckObject.setSourceCode(null);
            sqlBuffer.append("INSERT INTO R_SOURCE_TABLE (ID, SOURCE_CODE, TABLE_NAME, CN_NAME, SQL_STATEMENT, CREATE_USER, CREATE_TIME, UPDATE_USER, UPDATE_TIME, STATUS)" +
                    " VALUES('" + IdUtils.fastSimpleUUID() + "', NULL, '" + rCheckObject.getCheckCode() + "', '" + rCheckObject.getDescribes() + "', " +
                    "'" + rCheckObject.getSqlStatement() + "', NULL, SYSDATE, NULL, NULL, " + YssStatusEnum.NORMAL.getCode() + ");").append("\r\n");
        }
        sqlBuffer.append(SqlUtil.getSqlByList("R_CHECK_TYPE", rCheckTypeList, RCheckType.class));
        sqlBuffer.append(SqlUtil.getSqlByList("R_CHECK_OBJECT", rCheckObjectList, RCheckObject.class));
        return sqlBuffer.toString();
    }

    /**
     * 关联信息的 SQL
     *
     * @param rDatasetParFuncRelationList
     * @return
     */
    private String getRDatasetParFuncRelationSql(List<RDatasetParFuncRelation> rDatasetParFuncRelationList) {
        if (StringUtils.isEmpty(rDatasetParFuncRelationList)) {
            return "";
        }
        for (RDatasetParFuncRelation rDatasetParFuncRelation : rDatasetParFuncRelationList) {
            if (null != rDatasetParFuncRelation.getTypes() && 0 == rDatasetParFuncRelation.getTypes()) { // 参数分类  r_parameter_type
                rDatasetParFuncRelation.setRelationId(rParameterType.get(rDatasetParFuncRelation.getName()));
            }
            if (null != rDatasetParFuncRelation.getTypes() && 1 == rDatasetParFuncRelation.getTypes()) { // 常量分类 r_constant_type
                rDatasetParFuncRelation.setRelationId(rConstantType.get(rDatasetParFuncRelation.getName()));
            }
            if (null != rDatasetParFuncRelation.getTypes() && 2 == rDatasetParFuncRelation.getTypes()) { // 函数
                rDatasetParFuncRelation.setRelationId(rFunctionMap.get(rDatasetParFuncRelation.getName()));
            }
            rDatasetParFuncRelation.setObjectId(rCheckObjectMap.get(rDatasetParFuncRelation.getCheckCode()));
            rDatasetParFuncRelation.setId(IdUtils.fastSimpleUUID());
        }
        return SqlUtil.getSqlByList("R_DATASET_PAR_FUNC_RELATION", rDatasetParFuncRelationList, RDatasetParFuncRelation.class);
    }

    /**
     * 上下文入参 SQL
     *
     * @param rCheckInParameterList
     * @return
     */
    private String getRCheckInParameterSql(List<RCheckInParameter> rCheckInParameterList) {
        if (StringUtils.isEmpty(rCheckInParameterList)) {
            return "";
        }
        for (RCheckInParameter rCheckInParameter : rCheckInParameterList) {
            rCheckInParameter.setId(IdUtils.fastSimpleUUID());
            rCheckInParameter.setCheckObjectId(rCheckObjectMap.get(rCheckInParameter.getCheckCode()));
            rCheckInParameter.setStatus(YssStatusEnum.NORMAL.getCode());
        }
        return SqlUtil.getSqlByList("R_CHECK_IN_PARAMETER", rCheckInParameterList, RCheckInParameter.class);

    }

    /**
     * 出参表 SQL
     *
     * @param rCheckSqlOutParameterList
     * @return
     */
    private String getRCheckSqlOutParameterSql(List<RCheckSqlOutParameter> rCheckSqlOutParameterList) {
        if (StringUtils.isEmpty(rCheckSqlOutParameterList)) {
            return "";
        }
        for (RCheckSqlOutParameter rCheckSqlOutParameter : rCheckSqlOutParameterList) {
            rCheckSqlOutParameter.setId(IdUtils.fastSimpleUUID());
            rCheckSqlOutParameter.setCheckObjectId(rCheckObjectMap.get(rCheckSqlOutParameter.getCheckCode()));
            rCheckSqlOutParameter.setStatus(YssStatusEnum.NORMAL.getCode());
        }
        return SqlUtil.getSqlByList("R_CHECK_SQL_OUT_PARAMETER", rCheckSqlOutParameterList, RCheckSqlOutParameter.class);
    }

    /**
     * 规则列表 SQL
     *
     * @param rCheckRuleList
     * @return
     */
    private String getRCheckRuleSql(List<RCheckRule> rCheckRuleList) {
        if (StringUtils.isEmpty(rCheckRuleList)) {
            return "";
        }
        StringBuffer sqlBuffer = new StringBuffer();
        // 文件里的规则列表
        Map<String, String> checkRuleMap = new HashMap<>();
        for (RCheckRule rCheckRule : rCheckRuleList) {
            checkRuleMap.put(rCheckRule.getCheckCode() + TREE_SEPARATOR + rCheckRule.getRuleCode(), null);
        }
        // 库里的规则列表
        Map<String, String> checkRuleStaMap = new HashMap<>();
        List<RCheckRule> rCheckRuleStaList = rCheckRuleMapper.selectList(new QueryWrapper<>());
        if (StringUtils.isNotEmpty(rCheckRuleStaList)) {
            for (RCheckRule rCheckRule : rCheckRuleStaList) {
                if (!rCheckObjectMap.containsValue(rCheckRule.getCheckObjectId())) {
                    continue;
                }
                for (Map.Entry<String, String> m : rCheckObjectMap.entrySet()) {
                    if (rCheckRule.getCheckObjectId().equals(m.getValue())) {
                        checkRuleStaMap.put(m.getKey() + TREE_SEPARATOR + rCheckRule.getRuleCode(),
                                rCheckRule.getId());
                        break;
                    }
                }
            }
        }
        checkRuleMap.putAll(checkRuleStaMap);
        for (Map.Entry<String, String> entry : checkRuleMap.entrySet()) {
            if (StringUtils.isNotEmpty(entry.getValue())) {
                continue;
            }
            entry.setValue(IdUtils.fastSimpleUUID());
        }
        // 标准库 规则标签
        Map<String, String> labelMap = rRuleLabelMapper.selectList(new QueryWrapper<>()).
                stream().collect(Collectors.toMap(e -> e.getName(), e -> e.getId()));
        int i = 1;
        Map<String, Integer> labelMapTemp = new LinkedHashMap<>();
        for (RCheckRule rCheckRule : rCheckRuleList) {
            String ruleLabels = rCheckRule.getRuleLabels(); //标签
            if (StringUtils.isNotEmpty(ruleLabels)) {
                String[] arr = ruleLabels.split("，");
                for (int k = 0; k < arr.length; k++) {
                    if (labelMap.containsKey(arr[k])) {
                        continue;
                    }
                    labelMapTemp.put(arr[k], k);
                }
            }
        }
        List<Map.Entry<String, Integer>> list = new ArrayList<>(labelMapTemp.entrySet()); //将Map转换成List
        Collections.sort(list, Comparator.comparingInt(Map.Entry::getValue));
        Map<String, String> map2 = new LinkedHashMap<>();  // 这里必须声明成为LinkedHashMap，否则构造新map时会打乱顺序
        for (Map.Entry<String, Integer> o : list) {  // 构造新map
            map2.put(o.getKey(), IdUtils.fastSimpleData());
        }
        for (RCheckRule rCheckRule : rCheckRuleList) {
            String checkRuleId = checkRuleMap.get(rCheckRule.getCheckCode() + TREE_SEPARATOR + rCheckRule.getRuleCode());
            rCheckRule.setId(checkRuleId);
            rCheckRule.setStatus(YssStatusEnum.NORMAL.getCode());
            rCheckRule.setCheckObjectId(rCheckObjectMap.get(rCheckRule.getCheckCode()));
            rCheckRule.setSorts(i);
            String ruleLabels = rCheckRule.getRuleLabels(); //标签
            i++;
            if (StringUtils.isNotEmpty(ruleLabels)) {
                String[] arr = ruleLabels.split("，");
                for (String label : arr) {
                    if (labelMap.containsKey(label)) {
                        // 关联关系表
                        sqlBuffer.append("INSERT INTO R_RULE_LABEL_RELATION(ID,CHECK_RULE_ID, RULE_LABEL_ID)")
                                .append("VALUES('" + IdUtils.fastSimpleUUID() + "','" + checkRuleId + "','" + labelMap.get(label) + "');").append("\r\n");
                        continue;
                    }
                    String ruleLabelId = map2.get(label);
                    // 规则标签表 已经存在不用在生成
                    sqlBuffer.append("INSERT INTO R_RULE_LABEL(ID, NAME, CREATE_USER, CREATE_TIME, UPDATE_USER, UPDATE_TIME, STATUS)")
                            .append("VALUES('" + ruleLabelId + "', '" + label + "', NULL, SYSDATE, NULL, NULL, " + YssStatusEnum.NORMAL.getCode() + ");").append("\r\n");
                    labelMap.put(label, ruleLabelId);
                    // 关联关系表
                    sqlBuffer.append("INSERT INTO R_RULE_LABEL_RELATION(ID,CHECK_RULE_ID, RULE_LABEL_ID)")
                            .append("VALUES('" + IdUtils.fastSimpleUUID() + "','" + checkRuleId + "','" + ruleLabelId + "');").append("\r\n");
                }
            }
          /*  rCheckRule.getExpress().replaceAll("，", ",")
                    .replaceAll("（", "(")
                    .replaceAll("）", ")")
                    .replaceAll(" ", " ");
            String qlExpress = rCheckRule.getExpress();
            String ifExpress = qlExpress;
            String thenExpress = null;
            if (qlExpress.startsWith("如果") && qlExpress.indexOf("则") > 0) {
                int thenI = qlExpress.indexOf("则 ") > 0 ? qlExpress.indexOf("则 ") : qlExpress.indexOf("则\n") > 0 ? qlExpress.indexOf("则\n") : qlExpress.length();
                ifExpress = qlExpress.substring(3, thenI);
                if (thenI != qlExpress.length()) {
                    thenExpress = qlExpress.substring(thenI + 2);
                }
            }
            String[] ifFunctions = yssRule.getOutFunctionNames(ifExpress);
            String[] ifParams = yssRule.getOutVarNames(ifExpress.replaceAll("\\.","#"));
            paramNames.addAll(Arrays.asList(ifParams));
            funcNames.addAll(Arrays.asList(ifFunctions));*/
        }
        sqlBuffer.append(SqlUtil.getSqlByList("R_CHECK_RULE", rCheckRuleList, RCheckRule.class));
        return sqlBuffer.toString();
    }

    /**
     * 多表关联-关联条件
     *
     * @param rCheckObjectRelMappingList
     * @return
     */
    private String getRCheckObjectRelMapping(List<RCheckObjectRelMapping> rCheckObjectRelMappingList) {
        if (StringUtils.isEmpty(rCheckObjectRelMappingList)) {
            return "";
        }
        for (RCheckObjectRelMapping rCheckObjectRelMapping : rCheckObjectRelMappingList) {
            rCheckObjectRelMapping.setId(IdUtils.fastSimpleUUID());
            rCheckObjectRelMapping.setStatus(YssStatusEnum.NORMAL.getCode());
            rCheckObjectRelMapping.setLeftCheckObjectId(rCheckObjectMap.get(rCheckObjectRelMapping.getLeftCheckCode()));
            rCheckObjectRelMapping.setRightCheckObjectId(rCheckObjectMap.get(rCheckObjectRelMapping.getRelationCheckCode()));
        }
        return SqlUtil.getSqlByList("R_CHECK_OBJECT_REL_MAPPING", rCheckObjectRelMappingList, RCheckObjectRelMapping.class);
    }

    /**
     * 多表关联-分组字段
     *
     * @param rCheckObjectRelGroupbyList
     * @return
     */
    private String geRCheckObjectRelGroupby(List<RCheckObjectRelGroupby> rCheckObjectRelGroupbyList) {
        if (StringUtils.isEmpty(rCheckObjectRelGroupbyList)) {
            return "";
        }
        for (RCheckObjectRelGroupby rCheckObjectRelGroupby : rCheckObjectRelGroupbyList) {
            rCheckObjectRelGroupby.setId(IdUtils.fastSimpleUUID());
            rCheckObjectRelGroupby.setStatus(YssStatusEnum.NORMAL.getCode());
            rCheckObjectRelGroupby.setCheckObjectId(rCheckObjectMap.get(rCheckObjectRelGroupby.getCheckCode()));
        }
        return SqlUtil.getSqlByList("R_CHECK_OBJECT_REL_MAPPING", rCheckObjectRelGroupbyList, RCheckObjectRelGroupby.class);
    }

    /**
     * 多表关联-触发绑定
     *
     * @param rObjectSourceSqlRelationList
     * @return
     */
    private String getRObjectSourceSqlRelation(List<RObjectSourceSqlRelation> rObjectSourceSqlRelationList) {
        if (StringUtils.isEmpty(rObjectSourceSqlRelationList)) {
            return "";
        }
        for (RObjectSourceSqlRelation rObjectSourceSqlRelation : rObjectSourceSqlRelationList) {
            rObjectSourceSqlRelation.setId(IdUtils.fastSimpleUUID());
            rObjectSourceSqlRelation.setCheckObjectId(rCheckObjectMap.get(rObjectSourceSqlRelation.getCheckCode()));
        }
        return SqlUtil.getSqlByList("R_CHECK_OBJECT_REL_MAPPING", rObjectSourceSqlRelationList, RObjectSourceSqlRelation.class);
    }
}
